import React from 'react'
import ReactECharts from 'echarts-for-react'
import type { EChartsOption } from 'echarts'

export interface LineChartSeries {
  name: string
  data: Array<{ date: string; value: number }>
  color?: string
}

export interface LineChartProps {
  series: LineChartSeries[]
  height?: number | string
  title?: string
  yAxisName?: string
  smooth?: boolean
}

/**
 * 折线图组件
 * 用于时间序列数据展示
 */
const LineChart: React.FC<LineChartProps> = ({
  series,
  height = 400,
  title,
  yAxisName = '数值',
  smooth = true
}) => {
  // 提取所有日期
  const allDates = Array.from(
    new Set(series.flatMap(s => s.data.map(d => d.date)))
  ).sort()

  const option: EChartsOption = {
    title: title ? {
      text: title,
      left: 'center',
      textStyle: {
        fontSize: 16,
        fontWeight: 'normal'
      }
    } : undefined,
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        label: {
          backgroundColor: '#6a7985'
        }
      },
      formatter: (params: any) => {
        let result = `<div style="font-weight: bold; margin-bottom: 4px;">${params[0].axisValue}</div>`
        params.forEach((item: any) => {
          result += `<div>
            <span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:${item.color};"></span>
            ${item.seriesName}: ${item.value.toLocaleString()}
          </div>`
        })
        return result
      }
    },
    legend: {
      bottom: 10,
      data: series.map(s => s.name)
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '60px',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: allDates,
      axisLabel: {
        rotate: 45,
        fontSize: 11
      }
    },
    yAxis: {
      type: 'value',
      name: yAxisName,
      axisLabel: {
        formatter: (value: number) => {
          if (value >= 10000) {
            return (value / 10000).toFixed(1) + 'w'
          }
          return value.toString()
        }
      }
    },
    series: series.map(s => ({
      name: s.name,
      type: 'line',
      smooth,
      data: allDates.map(date => {
        const point = s.data.find(d => d.date === date)
        return point ? point.value : null
      }),
      lineStyle: {
        width: 2,
        color: s.color
      },
      itemStyle: {
        color: s.color
      },
      areaStyle: {
        opacity: 0.1,
        color: s.color
      }
    }))
  }

  return (
    <ReactECharts
      option={option}
      style={{ height, width: '100%' }}
      opts={{ renderer: 'canvas' }}
    />
  )
}

export default LineChart
